/*
 * @Author: wangdengduo
 * @Date: 2023-05-09 20:44:56
 * @LastEditors: wangdengduo
 * @LastEditTime: 2023-05-10 00:07:49
 * @FilePath: \todo-list\src\utils\mock.js
 * @Description:
 */

import Mock from "mockjs";

Mock.mock("/api/add", "post", (options) => {
  const body = JSON.parse(options.body);
  addData(body.data);
  return {};
});

Mock.mock("/api/update", "post", (options) => {
  const body = JSON.parse(options.body);
  updateData(body.data);
  return {};
});

Mock.mock("/api/del", "post", (options) => {
  const body = JSON.parse(options.body);
  delData(body.data);
  return {};
});

Mock.mock("/api/getList", "post", (options) => {
  return getData();
});

export const getData = () => {
  const jsonData = localStorage.getItem("todoData");
  const dataList = JSON.parse(jsonData);
  return dataList;
};

export const addData = (data) => {
  const jsonData = localStorage.getItem("todoData");
  let dataList = JSON.parse(jsonData) || [];
  if (dataList === null) {
    dataList = [];
  }
  dataList.unshift(data);
  localStorage.setItem("todoData", JSON.stringify(dataList));
};

export const updateData = (todo) => {
  const jsonData = localStorage.getItem("todoData");
  let dataList = JSON.parse(jsonData) || [];
  const newDataList = dataList.map((elem) => {
    if (elem.id === todo.id) {
      elem = todo;
    }
    return elem;
  });
  localStorage.setItem("todoData", JSON.stringify(newDataList));
};

export const delData = (id) => {
  const jsonData = localStorage.getItem("todoData");
  const dataList = JSON.parse(jsonData);
  const newDataList = dataList.filter((elem) => {
    return elem.id !== id;
  });
  localStorage.setItem("todoData", JSON.stringify(newDataList));
};
